<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Agent extends Backend_Controller {
	/*
	 * 构造函数
	 */

	public function __construct() {
		parent::__construct();
		$this->load->model('backend/Agent_model', 'Agent');
		$this->load->model('backend/Album_model', 'Album');
		$this->load->model('backend/Assignment_model', 'Assign');
		// 加载验证类
		$this->load->library('form_validation');
	}

	/*
	 * 显示后台供货商列表
	 */

	public function Index() {
		$this->isValidRequest();
		// 取得供货商列表
		$result = $this->Agent->getAgentAll($this->page, $this->input->post());
		$this->load->view('backend/agent/index', $result);
	}

	/**
	 * 删除供货商
	 */
	public function delete() {
		$this->isValidRequest();
		$ids = $this->input->post_get('ids');
		if ($this->Assign->deleteAssign($ids)) {
			$this->renderJson(200);
		}

		$this->renderJson(300);
	}

	/**
	 * 添加供货商
	 */
	public function add() {
		$this->isValidRequest();
		if ($this->isPost()) {
			$this->form_validation->validateData(array(
				'realname',
				'username',
				'password',
				'passwdConf',
				'district_id',
				'reverse_id',
				'autodyne_id',
				'front_id',
				'role',
				'status',
				'status2'
					), array(
				array(
					'realname',
					'required'
				),
				array(
					'username',
					'required|min_length[5]|is_unique[agent.username]'
				),
				array(
					'password',
					'required|min_length[6]'
				),
				array(
					'passwdConf',
					'required|matches[password]'
				),
				array(
					'district_id',
					'integer|greater_than[0]'
				),
				array(
					'reverse_id',
					'integer|greater_than[0]'
				),
				array(
					'autodyne_id',
					'integer|greater_than[0]'
				),
				array(
					'front_id',
					'integer|greater_than[0]'
				),
				array(
					'role',
					'integer|in_list[1,2]'
				),
				array(
					'status',
					'integer|in_list[0,10]'
				),
				array(
					'status2',
					'integer|in_list[0,10]'
				)
			));

			if ($this->form_validation->hasErrors()) {
				$this->renderJson(300, $this->form_validation->error);
			}

			$time = time();
			$data = array(
				'username' => $this->form_validation->username,
				'password_hash' => md5(md5(md5(md5($this->form_validation->password)))),
				'role' => $this->form_validation->role,
				'status' => $this->form_validation->status,
				'nickname' => $this->form_validation->realname,
				'address_id' => $this->form_validation->district_id,
				'created_at' => $time,
				'updated_at' => $time,
			);

			$data2 = array(
				'agent_id' => 0,
				'address_id' => $this->form_validation->district_id,
				'created_at' => $time,
				'updated_at' => $time,
				'status' => $this->form_validation->status2
			);
			$data3 = array(
				'agent_id' => 0,
				'realname' => $this->form_validation->realname,
				'autodyne_id' => $this->form_validation->autodyne_id,
				'front_id' => $this->form_validation->front_id,
				'reverse_id' => $this->form_validation->reverse_id,
				'created_at' => $time,
				'updated_at' => $time
			);
			$result = $this->Agent->addAgent($data, $data2, $data3);
			if ($result === true) {
				$this->renderJson(200, '', array(
					'navTabId' => 'backendagentindex',
					'callbackType' => 'closeCurrent'
				));
			}
			$this->lang->load('code');
			$this->renderJson(300, $this->lang->line("e{$result}"));
		}
		$this->load->view('backend/agent/add');
	}

	/**
	 * 修改管理员信息
	 */
	public function edit() {
		$this->isValidRequest();
		if ($this->isPost()) {
			$this->form_validation->validateData(array(
				'agid',
				'asid',
				'status',
				'status2'
					), array(
				array(
					'agid',
					'integer|greater_than[1]'
				),
				array(
					'asid',
					'integer|greater_than[1]'
				),
				array(
					'status',
					'integer'
				),
				array(
					'status2',
					'integer'
				)
			));

			if ($this->form_validation->hasErrors()) {
				$this->renderJson(300, $this->form_validation->error);
			}

			$data = array(
				'status' => $this->form_validation->status
			);
			if ($this->Agent->updateAgent($data, $this->form_validation->agid)) {

				$data2 = array(
					'status' => $this->form_validation->status2,
					'updated_at' => time()
				);
				if ($this->Assign->updateAssgin($data2, $this->form_validation->asid)) {
					$this->renderJson(200, '', array(
						'navTabId' => 'backendagentindex',
						'callbackType' => 'closeCurrent'
					));
				}
			}
			$this->renderJson(300);
		}
		$id = intval($this->get('id'));
		$result = $this->Agent->findAgent($id);
		$this->load->view('backend/agent/edit', $result);
	}

	/*
	 * 删除区域关系
	 */

	public function deleAssign() {
		$this->isValidRequest();
		$ids = $this->input->post_get('ids');
		if ($this->Assign->deleteAssign($ids)) {
			$this->renderJson(200, '', array(
				'navTabId' => 'backendagentedit'
			));
		}

		$this->renderJson(300);
	}

	/**
	 * 添加新地址
	 */
	public function addAdd() {
		$this->isValidRequest();
		if ($this->isPost()) {

			$this->form_validation->validateData(array(
				'id',
				'role'
					), array(
				array(
					'id',
					'integer|greater_than[1]'
				),
				array(
					'role',
					'greater_than[0]'
				)
			));

			if ($this->form_validation->hasErrors()) {
				$this->renderJson(300, $this->form_validation->error);
			}

			$data = array(
				'address_id' => $this->form_validation->role,
				'agent_id' => $this->form_validation->id,
				'created_at' => time()
			);


			if ($this->Assign->findAgentByN($data['address_id'], $data['agent_id'])) {
				$this->renderJson(300, '地址已经重复，请确认');
			}

			if ($this->Assign->addAssign($data)) {
				$this->renderJson(200);
			}
			$this->renderJson(300);
		}
		$id = intval($this->get('ids'));
		$result = array(
			'data' => $this->Agent->getAreasAll2(),
			'id' => $id
		);
		$this->load->view('backend/agent/addAdd', $result);
	}

	public function upload() {
		if (!empty($_FILES)) {
			$id = intval($this->post('id', 0));
			$source_id = intval($this->post('source_id', 0));
			
			$config ['upload_path'] = config_item('upload_path') . '/identification/' . date('Ymd');
			if (!is_dir($config ['upload_path'])) {
				mkdir($config ['upload_path'], 0755, true);
			}
			$config ['file_name'] = time() . rand(1000, 9999);
			$config ['allowed_types'] = 'jpg|bmp|jpeg|gif|png';

			$data = array(
				'status' => 300,
				'msg' => ''
			);

			$this->load->library('upload', $config);
			if (!$this->upload->do_upload('filedata')) {
				$data ['msg'] = $this->upload->display_errors();
			} else {
				$dataInsert = array(
					'source_id' => $source_id,
					'img' => $config ['upload_path'] . '/' . $this->upload->data('file_name'),
					'type' => '1', // 类型默认展示
					'from' => '4', // 来源身份证
				);
				if (!empty($id)) {
					$row = $this->Album->get_row(array('id' => $id));
					if (!empty($row['img']) && file_exists($row['img'])) {
						unlink($row['img']);
					}
					$this->Album->update($dataInsert, array('id' => $id));
					$data['id'] = $id;
				} else {
					$dataInsert['created_at'] = time();
					$data ['id'] = $this->Album->addOne($dataInsert);
				}
				$data ['filename'] = $dataInsert['img'];
				$data ['status'] = 200;
				$data ['msg'] = base_url($dataInsert ['img']);
			}
			if ($data ['status'] == 200) {
				$this->renderJson(200, $data ['msg'], array(
					'id' => $data ['id'],
					'filename' => $data['filename'],
					'id]' => $data ['id'],
					'filename]' => $data['filename']
				));
			} else {
				show_error($data ['msg']);
			}
		}
		$this->load->view('backend/agent/upload');
	}

}
